import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from lxml import etree
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from fake_useragent import UserAgent
import os
import execjs
import re
# def singlemusic_download(url):
# 第一版爬不了vip
    # s = Service('chromedriver.exe')
    # # 配置浏览器选项
    # options = Options()
    # options.add_argument("--headless")  # 无头模式
    # driver = webdriver.Chrome(service=s, options=options)
    # driver.get(url)
    # el_frame = driver.find_element(By.XPATH,'//*[@id="g_iframe"]')
    # driver.switch_to.frame(el_frame)
    # page = driver.page_source
    # driver.close()
    # ua = UserAgent()
    # random_ua = ua.random
    # headers = {
    #     'User-Agent': random_ua,
    #     'cookie': 'NMTID=00OQJ5yshJzQYj2mEkvo8ZHPvuLhvQAAAGVTDyuqw; _iuqxldmzr_=32; _ntes_nnid=9d0e9050d95c696295d296685dd846a2,1740740808397; _ntes_nuid=9d0e9050d95c696295d296685dd846a2; WEVNSM=1.0.0; WNMCID=zjycgq.1740740811362.01.0; WM_TID=Hh7JubJKxJxFVABBBRPHM2SgX6HnwXwD; ntes_utid=tid._.B%252BDqQPEvY%252FJAV1VRFFPTJnTgCuHtWALo._.0; sDeviceId=YD-NRqgtLB16XVFElBEUFKWREpF0W7vlaWx; __snaker__id=5fUK90Fl1NYlZ4qI; ntes_kaola_ad=1; NTES_YD_PASSPORT=HV0TXlTTjBsruht2xPHG1x.G0KDQMCB25Pb0tA_UJjbSTPr9Tw.qDBDmFYYiV2lFEY4nW3NC23vl0gE3Bfe5Ld9ze657yFCmAPV8g8iEFYt90fNQc5RxFnw9M4rz_IrKpTsfpN1cP6.hz_XmugfY0la9uRwT_GQlh.FHNNkmN3lRHuOkOkd6dfFBLRFxdAmDawtkxfBobCGxIuKaGImp1WAuWK9dEjIb8; P_INFO=15333564684|1741487038|1|phoenix_client|00&99|null&null&null#shx&140100#10#0|&0|null|15333564684; JSESSIONID-WYYY=RG1PVe3GI9MxDV%2BN%5CNXgYQYA2buwJxH9rMWhklQ7lpXiK%5C4dsFBt%2FmVq75C7KNh8o0Vi%5C%2FUXP2HnrVlaMd1San2%5C5tXwuHEVDDIWmM142QCvIKURqQoSrml0AuITeW80hv7SA23qE6EwJQm%2BcS9zpD%2FApH5ZwX%2Bdx4shgkAMJqrSRnQg%3A1742557090946; WM_NI=8XkDtIwl9po2xjFRsAF66XNw%2BbVc0khsTZ52EVRlu%2FnGSK47A%2B21H7PfMWr33jFDfYKylt5efOaZCq5CUjsbQKBtEG8Xw7fKqCYg5eApeMLD7WwM5jS9H2mt35WnUlslOXE%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eed8d77cbaf08db9bb3db0a88aa2c45f938f9a87db47fcf18aacc57a8b97bfb5cd2af0fea7c3b92afc88a5a5f743b5b4f791ee3abcb68ab3f24b86eafab9cd7de9be9a84b361acad9cbbb83a878a9e8df825ae999dacb73d83f5fed2cb3d94ba83b8f139f1b68aa5e55389a7a495b86fa691afbbc27bf79d9b8bf26a93958e95c84dfc88b9d8e541b39d9788b86f83b0abaecf50f589b9aeb86291e788d3f080f1eb998fd868b1b481b9c837e2a3; gdxidpyhxdE=8DtexyDIqHQ1DacR24hy3cHmBl1%2Fd7kHusKkARvC00cVA%5C8hDRxg%2Bfu5D2qoZgNCGG%2FH3rJ%2BOEwJpMNsqZ9nS4jnTJUmCOBqa5cvD2ouxyBm%2FOEP%2BWuAL4HZlk2xvUcrLos1dCHQ1NxR8M8ccB5wJUycX%2F9Snp3p%2Fe1xvs%2FKbBaESDT%2F%3A1742557015043; __csrf=b4b9faae4cb69d6aca12f8d4c0138ae1; MUSIC_U=003259A0001F4D6CA3B31016FDC477C0D2B308D36F6D2C82C9BDC723AD900AD261601E52AA2DF7EFF4A1423C59317764D0E99EE6D8D5BCE62DCFFCCA30A94589EF127ECB5303892C9ACF6BA8D6D52BDC6EB1E99839D97EFF7113038EBFAD49292BE18DC934B73AB9ADE3E1637CBB0BAD881906F7642F8B91B6C810E36247D9D6BA7D1AE1C8C08D3706F5C8DEBB4C631348707E0AB27719D63E0319FE536E92DAF00CAADE0F34BC6141BE83039667FA352C58C847DE230FDE38808022BB430F62657EFD01BC53C1C45904244469FFCBCBAC4040D08E7BA1A8A77439F27342DF0FF32936CEA95EC3FC85A5BD712E2458C69CA580EBB2E2BB3ADDD1F885B9DBC43DD22A4C1A082C950642BFA3FA97765C10F04DA9BA21B49D7755F12A5D0B89BA00E5283FA474219B41BBF757775B8505B39E4719DA2790CAB4909E15AAD1E5A09D1AB78F59FB438AE4BE3C000BFE1396CD4BFEE26FD6885A62C5F2B6405F4E9829FBE2F80BF0D83E46D5DF2F61B316605C12'
    # }
    #
    # path = etree.HTML(page)
    # title = path.xpath('//em[@class="f-ff2"]/text()')[0]
    # print(title)
    # id = url.split('=',1)[1]
    # out_url = "https://music.163.com/song/media/outer/url?id="
    # song_url = out_url + id
    #
    # if os.path.exists('音乐'):
    #     pass
    # else:
    #     os.mkdir('音乐')
    # r = requests.get(song_url, headers=headers)
    # with open (f'./音乐/{title}.mp3','wb') as f:
    #     f.write(r.content)
    # print(title+"下载成功")
# 第二版加上vip的cookie可爬vip
def MusicUrl(url):
    s = Service('../chromedriver.exe')
    # 配置浏览器选项
    options = Options()
    options.add_argument("--headless")  # 无头模式
    driver = webdriver.Chrome(service=s, options=options)
    driver.get(url)
    el_frame = driver.find_element(By.XPATH,'//*[@id="g_iframe"]')
    driver.switch_to.frame(el_frame)
    page = driver.page_source
    driver.close()
    path = etree.HTML(page)
    title = path.xpath('//em[@class="f-ff2"]/text()')[0]
    print(title)
    v1url = "https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token="
    file = open('../yiyun.js', 'r').read()
    id = url.split('=',1)[1]
    yiyun_js = execjs.compile(file)
    seckey = yiyun_js.call('result', int(id))
    data = {
            'params':seckey['encText'],
            'encSecKey':seckey['encSecKey']
        }
    headers = {
        'User-Agent': UserAgent().random,
        'Referer': 'https://music.163.com/',
        'cookie':'NMTID=00OQJ5yshJzQYj2mEkvo8ZHPvuLhvQAAAGVTDyuqw; _iuqxldmzr_=32; _ntes_nnid=9d0e9050d95c696295d296685dd846a2,1740740808397; _ntes_nuid=9d0e9050d95c696295d296685dd846a2; WEVNSM=1.0.0; WNMCID=zjycgq.1740740811362.01.0; WM_TID=Hh7JubJKxJxFVABBBRPHM2SgX6HnwXwD; ntes_utid=tid._.B%252BDqQPEvY%252FJAV1VRFFPTJnTgCuHtWALo._.0; sDeviceId=YD-NRqgtLB16XVFElBEUFKWREpF0W7vlaWx; __snaker__id=5fUK90Fl1NYlZ4qI; ntes_kaola_ad=1; NTES_YD_PASSPORT=HV0TXlTTjBsruht2xPHG1x.G0KDQMCB25Pb0tA_UJjbSTPr9Tw.qDBDmFYYiV2lFEY4nW3NC23vl0gE3Bfe5Ld9ze657yFCmAPV8g8iEFYt90fNQc5RxFnw9M4rz_IrKpTsfpN1cP6.hz_XmugfY0la9uRwT_GQlh.FHNNkmN3lRHuOkOkd6dfFBLRFxdAmDawtkxfBobCGxIuKaGImp1WAuWK9dEjIb8; P_INFO=15333564684|1741487038|1|phoenix_client|00&99|null&null&null#shx&140100#10#0|&0|null|15333564684; gdxidpyhxdE=8DtexyDIqHQ1DacR24hy3cHmBl1%2Fd7kHusKkARvC00cVA%5C8hDRxg%2Bfu5D2qoZgNCGG%2FH3rJ%2BOEwJpMNsqZ9nS4jnTJUmCOBqa5cvD2ouxyBm%2FOEP%2BWuAL4HZlk2xvUcrLos1dCHQ1NxR8M8ccB5wJUycX%2F9Snp3p%2Fe1xvs%2FKbBaESDT%2F%3A1742557015043; __csrf=b4b9faae4cb69d6aca12f8d4c0138ae1; MUSIC_U=003259A0001F4D6CA3B31016FDC477C0D2B308D36F6D2C82C9BDC723AD900AD261601E52AA2DF7EFF4A1423C59317764D0E99EE6D8D5BCE62DCFFCCA30A94589EF127ECB5303892C9ACF6BA8D6D52BDC6EB1E99839D97EFF7113038EBFAD49292BE18DC934B73AB9ADE3E1637CBB0BAD881906F7642F8B91B6C810E36247D9D6BA7D1AE1C8C08D3706F5C8DEBB4C631348707E0AB27719D63E0319FE536E92DAF00CAADE0F34BC6141BE83039667FA352C58C847DE230FDE38808022BB430F62657EFD01BC53C1C45904244469FFCBCBAC4040D08E7BA1A8A77439F27342DF0FF32936CEA95EC3FC85A5BD712E2458C69CA580EBB2E2BB3ADDD1F885B9DBC43DD22A4C1A082C950642BFA3FA97765C10F04DA9BA21B49D7755F12A5D0B89BA00E5283FA474219B41BBF757775B8505B39E4719DA2790CAB4909E15AAD1E5A09D1AB78F59FB438AE4BE3C000BFE1396CD4BFEE26FD6885A62C5F2B6405F4E9829FBE2F80BF0D83E46D5DF2F61B316605C12; JSESSIONID-WYYY=o2o6u2C%5C7NtIZkD9lC1zFkGoU991Ml60la3Sg%5C25awcbVgmyoPCB8XJ80eMevRzk86%5CtJrq%5C7a80E1YKKNbnBBvylKmeYbxN%5CVR7JcAalQbVU5rEb1R%2FW0%2FVNqPe2vab60JCrqx7xkKOeuBAtEcSWzvZu8lH5urBZyq0kpO%5CBDGICwqA%3A1742803331728; WM_NI=OpMy%2BZCe5ksV15k1sCjMmvzBEksHIqoRIeVxyeDsq6cA0LBxE3BnDvXyvl5W7HEPdNGARrVq8zcG8UZzVjCCoBcgAaN5iRwXWpfpkuw9%2B%2BfTCApZIXPDeL6fZ1YEH1h%2FU1E%3D; WM_NIKE=9ca17ae2e6ffcda170e2e6eea7cd60b499ae96f94da98a8fb3d14e939a9aadc642b29afab6ea59b3eafa96d62af0fea7c3b92a8db0839aaa5281bbfb8cf25ef3eba5d2f249aa93a397f94a87b5bda9cc7bad8e8786d574bbbb8c94f43ea19f00adc17487ed8e8fc77e9ca7ba8db85df5988bb1e746859f9e93d57bfca6ada8bb5f9aa69a8bc249ad9ead88c46b8eeba7b3f65495b0aa91ea7fb5e7e5cce560819fc0bbcc54949cabadb56e9aef97a6cb3bacf19bd2c837e2a3; playerid=52395351'
    }
    resp = requests.post(v1url, data=data, headers=headers)
    finurl = re.findall(r'url":"(.*?)"', resp.text)[0]
    return finurl,title
    # if os.path.exists('音乐'):
    #     pass
    # else:
    #     os.mkdir('音乐')
def downmusic(finurl,title,filename,cookie):

    headers = {
        'User-Agent': UserAgent().random,
        'Referer': 'https://music.163.com/',
        'cookie': cookie
    }
    r = requests.get(finurl, headers=headers)
    with open (f'{filename}','wb') as f:
        f.write(r.content)
    print(title+"下载成功")
def music_cover(url):
    s = Service('../chromedriver.exe')
    # 配置浏览器选项
    options = Options()
    options.add_argument("--headless")  # 无头模式
    driver = webdriver.Chrome(service=s, options=options)
    driver.get(url)
    el_frame = driver.find_element(By.XPATH, '//*[@id="g_iframe"]')
    driver.switch_to.frame(el_frame)
    page = driver.page_source
    driver.close()
    path = etree.HTML(page)
    coverurl = path.xpath('//div[@class="u-cover u-cover-6 f-fl"]/img/@src')[0]
    if coverurl:
        print("封面 URL:", coverurl)
    else:
        print("未找到封面 URL")
    if os.path.exists('../临时'):
        pass
    else:
        os.mkdir('../临时')
    imgname = 0
    imgurl=requests.get(coverurl)
    with open(f'../临时/cover{imgname}.jpg', 'wb') as f:
        f.write(imgurl.content)
    return coverurl


